package com.example.ercmssystem2.controller;

import com.example.ercmssystem2.entity.*;
import com.example.ercmssystem2.service.*;
import com.example.ercmssystem2.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/dispatch")
public class DispatchController {

    @Autowired
    private EventService eventService;

    @Autowired
    private UserService userService;

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private ResourceService resourceService;

    @Autowired
    private EventTypeService eventTypeService;

    @Autowired
    private NotificationService notificationService;

    @Autowired
    private JwtUtil jwtUtil;

    // 调度主界面
    @GetMapping
    public String dispatchMain(Model model) {
        // 暂时跳过后端认证检查，让前端处理认证
        // 这样可以避免JWT token在页面访问时无法正确设置Spring Security上下文的问题
        return "dispatch";
    }

    // 创建事件页面（简化路由）
    @GetMapping("/create")
    public String createEventShortcut() {
        return "redirect:/dispatch/create-event";
    }

    // 创建事件页面
    @GetMapping("/create-event")
    public String createEventPage(Model model) {
        // 暂时跳过后端认证检查，让前端处理认证
        
        // 获取事件类型
        List<EventType> eventTypes = eventTypeService.findAllEventTypes();
        model.addAttribute("eventTypes", eventTypes);

        // 获取可用部门
        List<Department> departments = departmentService.findAllDepartments();
        model.addAttribute("departments", departments);

        // 获取可用资源
        List<Resource> availableResources = resourceService.findAvailableResources();
        model.addAttribute("availableResources", availableResources);

        return "dispatch-create-event";
    }

    // 事件详情页面
    @GetMapping("/event/{id}")
    public String eventDetail(@PathVariable Long id, Model model) {
        // 暂时跳过后端认证检查，让前端处理认证
        
        Event event = eventService.findById(id);
        if (event == null) {
            return "redirect:/dispatch";
        }

        // 获取可用处理人
        List<User> availableHandlers = userService.getAvailableManagers();
        model.addAttribute("availableHandlers", availableHandlers);

        // 获取所有状态为可用的资源
        List<Resource> allAvailableResources = resourceService.findAvailableResources();

        // 获取已指派给此事件的资源
        List<Resource> assignedResources = eventService.findResourcesByEventId(id);
        model.addAttribute("assignedResources", assignedResources);

        // 从"所有可用"中过滤掉"已指派"的，得到真正可指派的列表
        List<Long> assignedResourceIds = assignedResources.stream().map(Resource::getId).collect(java.util.stream.Collectors.toList());
        List<Resource> assignableResources = allAvailableResources.stream()
                .filter(resource -> !assignedResourceIds.contains(resource.getId()))
                .collect(java.util.stream.Collectors.toList());
        model.addAttribute("availableResources", assignableResources);

        model.addAttribute("event", event);
        return "dispatch-event-detail";
    }

    // API: 创建事件
    @PostMapping("/api/events")
    @ResponseBody
    public ResponseEntity<?> createEvent(@RequestBody Map<String, Object> eventData, 
                                       @RequestHeader(value = "Authorization", required = false) String authHeader) {
        // 从JWT token中获取用户信息
        User currentUser = getUserFromJwt(authHeader);
        if (currentUser == null) {
            return ResponseEntity.status(401).body(Map.of("success", false, "message", "未登录"));
        }

        try {
            Event event = new Event();
            event.setTitle((String) eventData.get("title"));
            event.setDescription((String) eventData.get("description"));
            event.setLocation((String) eventData.get("location"));
            event.setPriority((String) eventData.get("priority"));
            event.setSeverity((String) eventData.get("severity"));
            
            // 处理坐标信息
            String lnglat = (String) eventData.get("lnglat");
            System.out.println("收到坐标数据: " + lnglat); // 调试日志
            if (lnglat != null && !lnglat.trim().isEmpty()) {
                try {
                    String[] coordinates = lnglat.split(",");
                    if (coordinates.length == 2) {
                        double longitude = Double.parseDouble(coordinates[0].trim());
                        double latitude = Double.parseDouble(coordinates[1].trim());
                        // 将坐标保存到Event.location字段
                        event.setLocation(lnglat);
                        event.setLastLocationUpdate(LocalDateTime.now());
                        System.out.println("坐标解析成功 - 经度: " + longitude + ", 纬度: " + latitude); // 调试日志
                    } else {
                        System.out.println("坐标格式错误，期望格式: 经度,纬度，实际: " + lnglat); // 调试日志
                    }
                } catch (NumberFormatException e) {
                    // 坐标格式错误，记录日志但不影响事件创建
                    System.err.println("坐标格式错误: " + lnglat + ", 错误: " + e.getMessage());
                }
            } else {
                System.out.println("未收到坐标数据或坐标为空"); // 调试日志
            }
            
            // 设置事件类型
            Long eventTypeId = Long.valueOf(eventData.get("eventTypeId").toString());
            EventType eventType = eventTypeService.findById(eventTypeId);
            event.setEventType(eventType);
            
            // 设置报告人
            event.setReporter(currentUser);
            
            // 设置开始时间
            event.setStartTime(LocalDateTime.now());
            
            // 设置状态
            event.setStatus("PENDING");
            
            Event savedEvent = eventService.saveEvent(event);
            
            // 验证保存的坐标
            System.out.println("事件保存成功，ID: " + savedEvent.getId() + 
                             ", 位置: " + savedEvent.getLocation()); // 调试日志
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "事件创建成功");
            response.put("data", savedEvent);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "创建事件失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    // API: 获取事件详情
    @GetMapping("/api/events/{eventId}")
    @ResponseBody
    public ResponseEntity<?> getEventDetail(@PathVariable Long eventId,
                                          @RequestHeader(value = "Authorization", required = false) String authHeader) {
        User currentUser = getUserFromJwt(authHeader);
        if (currentUser == null) {
            return ResponseEntity.status(401).body(Map.of("success", false, "message", "未登录"));
        }
        try {
            Event event = eventService.findById(eventId);
            if (event == null) {
                return ResponseEntity.badRequest().body(Map.of("success", false, "message", "事件不存在"));
            }
            // 获取事件的处理人和资源历史
            List<EventResponse> progressHistory = eventService.getEventProgressHistory(eventId);
            List<EventResource> resourceHistory = eventService.getResourceHistoryByEventId(eventId);
            List<EventResource> currentResources = eventService.findCurrentEventResources(eventId);

            if ("RESOLVED".equals(event.getStatus()) || "CLOSED".equals(event.getStatus())) {
                currentResources = List.of();
            }

            // 组装处理人-资源绑定关系
            List<Map<String, Object>> assignedUnits = new java.util.ArrayList<>();
            for (EventResource er : currentResources) {
                Map<String, Object> unit = new HashMap<>();
                unit.put("handler", er.getHandler());
                unit.put("resource", er.getResource());
                assignedUnits.add(unit);
            }

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", event);
            response.put("progressHistory", progressHistory);
            response.put("resourceHistory", resourceHistory);
            response.put("assignedUnits", assignedUnits);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of("success", false, "message", e.getMessage()));
        }
    }

    // API: 指派处理人和资源
    @PostMapping("/api/events/{eventId}/assign")
    @ResponseBody
    public ResponseEntity<?> assignHandlerAndResources(@PathVariable Long eventId, 
                                                      @RequestBody Map<String, Object> assignData,
                                                      @RequestHeader(value = "Authorization", required = false) String authHeader) {
        User currentUser = getUserFromJwt(authHeader);
        if (currentUser == null) {
            return ResponseEntity.status(401).body(Map.of("success", false, "message", "未登录"));
        }
        try {
            Event event = eventService.findById(eventId);
            if (event == null) {
                return ResponseEntity.badRequest().body(Map.of("success", false, "message", "事件不存在"));
            }
            if ("RESOLVED".equals(event.getStatus()) || "CLOSED".equals(event.getStatus())) {
                return ResponseEntity.badRequest().body(Map.of("success", false, "message", "事件已解决或关闭，无法再指派"));
            }
            Long handlerId = assignData.get("handlerId") != null ? Long.valueOf(assignData.get("handlerId").toString()) : null;
            List<Integer> resourceIds = (List<Integer>) assignData.get("resourceIds");
            List<Long> resourceIdList = resourceIds != null ? resourceIds.stream().map(Long::valueOf).toList() : List.of();
            Event updatedEvent = eventService.assignEvent(eventId, handlerId, resourceIdList);
            return ResponseEntity.ok(Map.of("success", true, "message", "指派成功", "data", updatedEvent));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of("success", false, "message", "指派失败: " + e.getMessage()));
        }
    }

    // API: 为事件指派资源
    @PostMapping("/api/events/{eventId}/assign-resources")
    @ResponseBody
    public ResponseEntity<?> assignResourcesToEvent(@PathVariable Long eventId, 
                                                   @RequestBody Map<String, List<Long>> payload,
                                                   @RequestHeader(value = "Authorization", required = false) String authHeader) {
        User currentUser = getUserFromJwt(authHeader);
        if (currentUser == null) {
            return ResponseEntity.status(401).body(Map.of("success", false, "message", "未登录"));
        }
        try {
            Event event = eventService.findById(eventId);
            if (event == null) {
                return ResponseEntity.badRequest().body(Map.of("success", false, "message", "事件不存在"));
            }
            if ("RESOLVED".equals(event.getStatus()) || "CLOSED".equals(event.getStatus())) {
                return ResponseEntity.badRequest().body(Map.of("success", false, "message", "事件已解决或关闭，无法再指派单位"));
            }
            List<Long> resourceIds = payload.get("resourceIds");
            eventService.assignResourcesToEvent(eventId, resourceIds, currentUser.getId());
            return ResponseEntity.ok(Map.of("success", true, "message", "资源指派成功"));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of("success", false, "message", "资源指派失败: " + e.getMessage()));
        }
    }

    // API: 更新事件进度
    @PostMapping("/api/events/{eventId}/progress")
    @ResponseBody
    public ResponseEntity<?> updateEventProgress(@PathVariable Long eventId, 
                                                @RequestBody Map<String, Object> progressData,
                                                @RequestHeader(value = "Authorization", required = false) String authHeader) {
        User currentUser = getUserFromJwt(authHeader);
        if (currentUser == null) {
            return ResponseEntity.status(401).body(Map.of("success", false, "message", "未登录"));
        }
        try {
            String progress = (String) progressData.get("progress");
            String status = (String) progressData.get("status");
            Event event = eventService.updateEventProgress(eventId, progress, status);
            return ResponseEntity.ok(Map.of("success", true, "message", "进度已更新", "data", event));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of("success", false, "message", "进度更新失败: " + e.getMessage()));
        }
    }

    // API: 获取事件列表
    @GetMapping("/api/events")
    @ResponseBody
    public ResponseEntity<?> getEvents(@RequestParam(defaultValue = "0") int page,
                                      @RequestParam(defaultValue = "10") int size,
                                      @RequestParam(required = false) String status,
                                      @RequestParam(required = false) String priority,
                                      @RequestHeader(value = "Authorization", required = false) String authHeader) {
        User currentUser = getUserFromJwt(authHeader);
        if (currentUser == null) {
            return ResponseEntity.status(401).body(Map.of("success", false, "message", "未登录"));
        }

        try {
            List<Event> events = eventService.findAllEvents();
            
            // 根据状态筛选
            if (status != null && !status.isEmpty()) {
                events = events.stream()
                    .filter(event -> status.equals(event.getStatus()))
                    .toList();
            }
            
            // 根据优先级筛选
            if (priority != null && !priority.isEmpty()) {
                events = events.stream()
                    .filter(event -> priority.equals(event.getPriority()))
                    .toList();
            }
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", events);
            response.put("total", events.size());
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取事件列表失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    // API: 获取可用资源
    @GetMapping("/api/resources/available")
    @ResponseBody
    public ResponseEntity<?> getAvailableResources(@RequestHeader(value = "Authorization", required = false) String authHeader) {
        User currentUser = getUserFromJwt(authHeader);
        if (currentUser == null) {
            return ResponseEntity.status(401).body(Map.of("success", false, "message", "未登录"));
        }

        try {
            List<Resource> resources = resourceService.findAvailableResources();
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", resources);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取资源列表失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    // API: 获取用户通知
    @GetMapping("/api/notifications")
    @ResponseBody
    public ResponseEntity<?> getUserNotifications(@RequestHeader(value = "Authorization", required = false) String authHeader) {
        User currentUser = getUserFromJwt(authHeader);
        if (currentUser == null) {
            return ResponseEntity.status(401).body(Map.of("success", false, "message", "未登录"));
        }

        try {
            List<Notification> notifications = notificationService.getUserNotifications(currentUser.getId());
            Long unreadCount = notificationService.getUnreadCount(currentUser.getId());
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", notifications);
            response.put("unreadCount", unreadCount);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取通知失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    // API: 标记通知为已读
    @PostMapping("/api/notifications/{notificationId}/read")
    @ResponseBody
    public ResponseEntity<?> markNotificationAsRead(@PathVariable Long notificationId,
                                                   @RequestHeader(value = "Authorization", required = false) String authHeader) {
        User currentUser = getUserFromJwt(authHeader);
        if (currentUser == null) {
            return ResponseEntity.status(401).body(Map.of("success", false, "message", "未登录"));
        }

        try {
            Notification notification = notificationService.markAsRead(notificationId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "通知已标记为已读");
            response.put("data", notification);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "操作失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    // API: 标记所有通知为已读
    @PostMapping("/api/notifications/read-all")
    @ResponseBody
    public ResponseEntity<?> markAllNotificationsAsRead(@RequestHeader(value = "Authorization", required = false) String authHeader) {
        User currentUser = getUserFromJwt(authHeader);
        if (currentUser == null) {
            return ResponseEntity.status(401).body(Map.of("success", false, "message", "未登录"));
        }

        try {
            notificationService.markAllAsRead(currentUser.getId());
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "所有通知已标记为已读");
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "操作失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    // API: 指派处理人
    @PostMapping("/api/events/{eventId}/assign-handler")
    @ResponseBody
    public ResponseEntity<?> assignHandler(@PathVariable Long eventId, 
                                          @RequestBody Map<String, Long> payload,
                                          @RequestHeader(value = "Authorization", required = false) String authHeader) {
        User currentUser = getUserFromJwt(authHeader);
        if (currentUser == null) {
            return ResponseEntity.status(401).body(Map.of("success", false, "message", "未登录"));
        }
        try {
            Event event = eventService.findById(eventId);
            if (event == null) {
                return ResponseEntity.badRequest().body(Map.of("success", false, "message", "事件不存在"));
            }
            if ("RESOLVED".equals(event.getStatus()) || "CLOSED".equals(event.getStatus())) {
                return ResponseEntity.badRequest().body(Map.of("success", false, "message", "事件已解决或关闭，无法再指派处理人"));
            }
            Long handlerId = payload.get("handlerId");
            if (handlerId == null) {
                return ResponseEntity.badRequest().body(Map.of("success", false, "message", "未选择处理人"));
            }
            User handler = userService.findById(handlerId);
            eventService.assignHandler(eventId, handler);
            return ResponseEntity.ok(Map.of("success", true, "message", "处理人指派成功"));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of("success", false, "message", "处理人指派失败: " + e.getMessage()));
        }
    }

    // 从JWT token中获取用户信息的辅助方法
    private User getUserFromJwt(String authHeader) {
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            return null;
        }
        
        try {
            String token = authHeader.substring(7);
            if (jwtUtil.validateToken(token)) {
                String username = jwtUtil.extractUsername(token);
                return userService.findByUsername(username);
            }
        } catch (Exception e) {
            // Token无效或解析失败
        }
        
        return null;
    }
} 